package logs

import (
	"time"

	"gitee.com/xgotool/sqlite-logs-more/model"
	"gitee.com/xgotool/sqlite-logs-more/service/rootdb"
	"gitee.com/xiaoyutab/xgotool/sdk/xgorm"
	"gitee.com/xiaoyutab/xgotool/xstring"
)

type LogSearch struct {
	Type       string             `json:"type" form:"type"`               // 日志类型, open_error-日志打开失败 pipe-管道日志 app-APP运行日志 runtime-运行耗时日志 quest-三方接口请求日志
	FileName   string             `json:"file_name" form:"file_name"`     // 日志文件名称
	Error      string             `json:"error" form:"error"`             // 错误详情
	PipeLog    []model.PipeLog    `json:"pipe_log" form:"pipe_log"`       // 通道错误列表，只搜索content值
	AppLog     []model.AppLog     `json:"app_log" form:"app_log"`         // APP错误列表, 只搜索content值
	RuntimeLog []model.RuntimeLog `json:"runtime_log" form:"runtime_log"` // 运行耗时列表，只有针对某条记录查询时才会进行展示
	QuestLog   []model.QuestLog   `json:"quest_log" form:"quest_log"`     // 请求日志列表，只搜素uri、param、body、error、uuid、ruid
}

// 搜索全部地址
//
//	start_time	开始时间
func AllLogSearch(start_time, end_time string, dervice_id int64, args, keys string) ([]LogSearch, error) {
	if start_time != "" {
		start_time += " 00:00:00"
	}
	if end_time != "" {
		end_time += " 23:59:59"
	}
	// 时间格式化
	start_time_search, end_time_search := xstring.ToTime(start_time), xstring.ToTime(end_time)
	if start_time_search.Unix() == 0 {
		start_time_search = time.Now().AddDate(0, 0, -7)
	}
	if end_time_search.Unix() <= 0 {
		end_time_search = time.Now()
	}
	// 获取当前存在的设备列表
	files, err := rootdb.FileListAll(start_time_search.UnixNano(), end_time_search.UnixNano())
	if err != nil {
		return nil, err
	}
	rets := []LogSearch{}
	// 进行pipe日志搜索
	for i := 0; i < len(files); i++ {
		db, err := connect_file(files[i].Path)
		if err != nil {
			rets = append(rets, LogSearch{
				Type:     "open_error",
				FileName: files[i].Name,
				Error:    err.Error(),
			})
			continue
		}
		// pipe日志
		pipe_info := LogSearch{
			Type:     "pipe",
			FileName: files[i].Name,
		}
		pip, pips := model.PipeLog{}, []model.PipeLog{}
		pipe_db := db.Table(pip.TableName()).
			Where("id >= ?", start_time_search.UnixNano()).
			Where("id < ?", end_time_search.AddDate(0, 0, 1).UnixNano())
		if dervice_id > 0 {
			pipe_db.Where("did", dervice_id)
		}
		if args != "" {
			pipe_db.Where("args", args)
		}
		if keys != "" {
			pipe_db.Where("content LIKE ?", "%"+keys+"%")
		}
		// 数据搜索
		err = pipe_db.Order("id DESC").Find(&pips).Error
		if err != nil {
			pipe_info.Error = err.Error()
		}
		pipe_info.PipeLog = pips
		rets = append(rets, pipe_info)

		// app日志
		app_info := LogSearch{
			Type:     "app",
			FileName: files[i].Name,
		}
		app, apps := model.AppLog{}, []model.AppLog{}
		app_db := db.Table(app.TableName()).
			Where("id >= ?", start_time_search.UnixNano()).
			Where("id < ?", end_time_search.AddDate(0, 0, 1).UnixNano())
		if dervice_id > 0 {
			app_db.Where("did", dervice_id)
		}
		if args != "" {
			app_db.Where("args", args)
		}
		if keys != "" {
			app_db.Where("content LIKE ?", "%"+keys+"%")
		}
		// 数据搜索
		err = app_db.Order("id DESC").Find(&apps).Error
		if err != nil {
			app_info.Error = err.Error()
		}
		app_info.AppLog = apps
		rets = append(rets, app_info)

		// quest日志搜素
		quest_info := LogSearch{
			Type:     "quest",
			FileName: files[i].Name,
		}
		quest, quests := model.QuestLog{}, []model.QuestLog{}
		quest_db := db.Table(quest.TableName()).
			Where("id >= ?", start_time_search.UnixNano()).
			Where("id < ?", end_time_search.AddDate(0, 0, 1).UnixNano())
		if dervice_id > 0 {
			quest_db.Where("did", dervice_id)
		}
		if args != "" {
			quest_db.Where("args", args)
		}
		if keys != "" {
			// 搜索字段列表
			args_temp := []string{"uri", "param", "body", "error", "header", "uuid", "ruid"}
			quest_db = xgorm.To(quest_db).Likes(args_temp, "%"+keys+"%").DB
		}
		// 数据搜索
		err = quest_db.Order("id DESC").Find(&quests).Error
		if err != nil {
			app_info.Error = err.Error()
		}
		quest_info.QuestLog = quests
		rets = append(rets, quest_info)
	}
	return rets, nil
}
